import http from './https.js'
import bigNumber from '@/common/js/bignumber.js'
import permision from "@/js_sdk/wa-permission/permission.js"
import show_modal_fun from '@/utils/modal/modal.js'
import md5 from 'js-md5'
let Base64 = require('js-base64').Base64
var timestamp = Date.parse(new Date()) / 1000

let os = uni.getDeviceInfo().platform

let modal = function(content, callback = function() {
	uni.navigateBack()
}, title = '', delCancel = true) {
	if (os == "android") {
		show_modal_fun({
			title: title, //可选,不填则不显示
			content: content,
			confirmVal: '确定', // 可选
			delCancel: delCancel
		}).then(res => {
			callback()
		}).catch(res => {})
	} else {
		uni.showModal({
			title: title,
			content: content,
			showCancel: !delCancel,
			success(res) {
				if (res.confirm) {
					callback()
				}
			}
		})
	}
}

let authorize = async function(permisionID) {
	var result = await permision.requestAndroidPermission(permisionID)
	return result
}

// CALLPHONE				拨打电话权限
// LOCATION					获取定位权限
// CAMERA 					摄像头权限
// READ_EXTERNAL_STORAGE	外部存储(含相册)读取权限
// WRITE_EXTERNAL_STORAGE	外部存储(含相册)写入权限
// RECORD_AUDIO				麦克风权限

let msg = function(message) {
	uni.showToast({
		title: message,
		duration: 2000,
		icon: "none"
	});
}
let phoneVerify = function(phoneNumber) {
	if (phoneNumber.length !== 11) { // 判断是否为11位数字
		msg("手机号格式不正确")
		return false;
	}
	for (var i = 0; i < phoneNumber.length; i++) {
		if (phoneNumber.charAt(i) < "0" || phoneNumber.charAt(i) > "9") { // 判断是否为数字
			msg("手机号格式不正确")
			return false;
		}
	}
	if (phoneNumber.charAt(0) !== "1") { // 判断首位是否为1
		msg("手机号格式不正确")
		return false;
	}
	return true; // 满足以上条件则为合法手机号码
}
let imgUrl = 'https://qiniu-cdn.maeiyun.com/'
let imgurl = function(url) { //图片地址拼接
	return imgUrl + '' + url
}
function createSign() {
	timestamp = Date.parse(new Date()) / 1000
	let last_num = timestamp.toString().slice(-1)
	if (last_num <= 3) {
		last_num = 3;
	} else if (last_num > 3 && last_num <= 6) {
		last_num = 6;
	} else if (last_num > 6 && last_num <= 9) {
		last_num = 9;
	} else {
		last_num = 0;
	}
	let new_str = timestamp.toString().slice(0, 9)
	let md5_str = md5(new_str);
	let str_split = md5_str.split('')
	let new_str_split = str_split.sort()
	return Base64.encode(new_str_split.join("") + '&time=' + timestamp);
}
var token = '';
let upload = function(type, file, callback, add_water = 0) {
	uni.showLoading({
		title: '上传中',
	})
	try {
		token = uni.getStorageSync('token');
	} catch (e) {
		// error
	}
	uni.uploadFile({
		url: http.baseUrl + 'upload/permanent', //仅为示例，非真实的接口地址
		filePath: file,
		header: {
			'token': token,
			'sign': createSign(),
		},
		name: 'file',
		formData: {
			'type': type,
			add_water: add_water,
		},
		success: (uploadFileRes) => {
			uni.hideLoading()
			let res = JSON.parse(uploadFileRes.data)
			if (res.code == 0) {
				if (res.data.status == 2) {
					callback({
						code: 0,
						data: {
							...res.data.result
						}
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		},
		fail() {
			uni.hideLoading()
		}
	});
}
let hasEmptyValue = function(obj) { // 对象是否包含空值
	var returnObj = {}
	for (var key in obj) {
		if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
			returnObj.status = true
			returnObj.value = key
			return returnObj;
		}
	}
	return false;
}

let transitionLocation = function(lat, lng, callback) { //逆地址转换
	http.httpTokenRequest({
		url: "index/getLocationByLocation",
		method: "post"
	}, {
		lat: lat,
		lng: lng,
	}).then(data => {
		callback(data)
	})
}
let newDayDate = function(time) {
	var date = new Date(time)
	var y = date.getFullYear()
	var m = date.getMonth() + 1
	m = m < 10 ? '0' + m : m
	var d = date.getDate()
	d = d < 10 ? '0' + d : d
	return m + '-' + d
}
let getDate = function(type) {
	var date = ""
	if (type == 0) { //今天
		var today = new Date();
		var year = today.getFullYear();
		var month = today.getMonth() + 1; // 月份从 0 开始计数，所以需要加 1
		var day = today.getDate();
		date = year + "-" + month + "-" + day;
	} else { //明天
		var today = new Date();
		var tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000); // 加上一天的毫秒数
		var year = tomorrow.getFullYear();
		var month = tomorrow.getMonth() + 1; // 月份从 0 开始计数，所以需要加 1
		var day = tomorrow.getDate();
		date = year + "-" + month + "-" + day;
	}
	return date
}

let makeCall = function(data) {
	if (os == 'ios') {
		uni.makePhoneCall({
			phoneNumber: data + '',
			success: res => {
				// console.log(res);
			},
			fail: err => {
				// console.log(err, 'makePhoneCall:fail');
			}
		})
	} else {
		if (uni.getStorageSync('CALLPHONE')) {
			uni.makePhoneCall({
				phoneNumber: data + '',
				success: res => {
					// console.log(res);
				},
				fail: err => {
					// console.log(err, 'makePhoneCall:fail');
					uni.showToast({
						title:'拨打电话失败，请检查权限是否开启'
					})
					uni.openAppAuthorizeSetting()
				}
			})
		} else {
			modal('将获取您的快捷拨号权限进行拨打电话', () => {
				uni.setStorageSync('CALLPHONE', true)
				uni.makePhoneCall({
					phoneNumber: data + '',
					success: res => {},
					fail: err => {
						uni.showToast({
							title:'拨打电话失败，请检查权限是否开启'
						})
						uni.openAppAuthorizeSetting()
						// console.log(err, 'makePhoneCall:fail');
					}
				})
			})
		}
	}
}

let chooseImage = function(data, callback, extension = true) {
	if (os == 'ios') {
		uni.chooseImage({
			...data,
			extension: extension ? ['jpg', 'png', 'jpeg'] : null,
			success: res => {
				callback(res)
			}
		})
	} else {
		if (uni.getStorageSync('READ_EXTERNAL_STORAGE')) {
			uni.chooseImage({
				...data,
				extension: extension ? ['jpg', 'png', 'jpeg'] : null,
				sourceType: ['album'],
				success: res => {
					callback(res)
				}
			})
		} else {
			modal('将获取您的相册读取权限，实现上传头像、认证资料等功能', () => {
				uni.setStorageSync('READ_EXTERNAL_STORAGE', true)
				uni.chooseImage({
					...data,
					extension: extension ? ['jpg', 'png', 'jpeg'] : null,
					sourceType: ['album'],
					success: res => {
						callback(res)
					}
				})
			})
		}
	}
}

let chooseVideo = function(data, callback, extension = true) {
	if (os == 'ios') {
		uni.chooseVideo({
			...data,
			success: res => {
				callback(res)
			}
		})
	} else {
		if (uni.getStorageSync('READ_EXTERNAL_STORAGE')) {
			uni.chooseVideo({
				...data,
				success: res => {
					callback(res)
				}
			})
		} else {
			modal('将获取您的相册读取权限，实现上传头像、认证资料等功能', () => {
				uni.setStorageSync('READ_EXTERNAL_STORAGE', true)
				uni.chooseVideo({
					...data,
					success: res => {
						callback(res)
					}
				})
			})
		}
	}
}

let toUrl = function(url, type = 'navigateTo') {
	if (type == 'navigateTo') {
		uni.navigateTo({
			url: url
		})
	}
	if (type == 'redirectTo') {
		uni.redirectTo({
			url: url
		})
	}
	if (type == 'reLaunch') {
		uni.reLaunch({
			url: url
		})
	}
}



let idcardVerify = function(idcard) {
	var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
	return p.test(idcard)
}
let phoneType = function() {
	var type = ""
	uni.getSystemInfo({
		success: res => {
			type = res.osName
		}
	})
	return type
}

let getLocation = function(callback) {
	if (os == 'ios') {
		uni.showLoading({
			mask: true
		})
		uni.getLocation({
			geocode: true,
			type: phoneType() == 'android' ? 'gcj02' : 'wgs84',
			altitude: true,
			accuracy: 'high',
			success: res => {
				uni.hideLoading()
				callback(res)
			},
			fail: err => {
				uni.hideLoading()
				callback(false)
			}
		})
	} else {
		if (uni.getStorageSync('LOCATION')) {
			uni.showLoading({
				mask: true
			})
			uni.getLocation({
				geocode: true,
				type: phoneType() == 'android' ? 'gcj02' : 'wgs84',
				success: res => {
					uni.hideLoading()
					callback(res)
				},
				fail: err => {
					uni.hideLoading()
					callback(false)
				}
			})
		} else {
			modal('为了更好的向您推荐周边的酒店、景区和生活服务等，我们将访问您的位置信息，', () => {
				uni.setStorageSync('LOCATION', true)
				uni.showLoading({
					mask: true
				})
				uni.getLocation({
					geocode: true,
					type: phoneType() == 'android' ? 'gcj02' : 'wgs84',
					success: res => {
						uni.hideLoading()
						callback(res)
					},
					fail: err => {
						uni.hideLoading()
						callback(false)
					}
				})
			})
		}
	}
}

let scanCode = function(callback) {
	if (os == 'ios') {
		uni.scanCode({
			success: res => {
				callback(res)
			}
		})
	} else {
		if (uni.getStorageSync('CAMERA')) {
			uni.scanCode({
				success: res => {
					callback(res)
				}
			})
		} else {
			modal('将获取您的摄像头权限，实现扫码功能', () => {
				uni.setStorageSync('CAMERA', true)
				uni.scanCode({
					success: res => {
						callback(res)
					}
				})
			})
		}
	}
}


let luhnCheck = function(bankno) {
	var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）
	var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
	var newArr = new Array();
	for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
		newArr.push(first15Num.substr(i, 1));
	}
	var arrJiShu = new Array(); //奇数位*2的积 <9
	var arrJiShu2 = new Array(); //奇数位*2的积 >9
	var arrOuShu = new Array(); //偶数位数组
	for (var j = 0; j < newArr.length; j++) {
		if ((j + 1) % 2 == 1) { //奇数位
			if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
			else arrJiShu2.push(parseInt(newArr[j]) * 2);
		} else //偶数位
			arrOuShu.push(newArr[j]);
	}

	var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
	var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
	for (var h = 0; h < arrJiShu2.length; h++) {
		jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
		jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
	}

	var sumJiShu = 0; //奇数位*2 < 9 的数组之和
	var sumOuShu = 0; //偶数位数组之和
	var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
	var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
	var sumTotal = 0;
	for (var m = 0; m < arrJiShu.length; m++) {
		sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
	}

	for (var n = 0; n < arrOuShu.length; n++) {
		sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
	}

	for (var p = 0; p < jishu_child1.length; p++) {
		sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
		sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
	}
	//计算总和
	sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

	//计算luhn值
	var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
	var luhn = 10 - k;

	if (lastNum == luhn) {
		return true;
	} else {
		return false;
	}
}

function compareVersion(version1, version2) {
  if (version1 === '' || version2 === '') {
    throw new Error('版本号不能为空')
  }
  const arr1 = version1.split('.')
  const arr2 = version2.split('.')
  const length1 = arr1.length
  const length2 = arr2.length
  let minlength = Math.min(length1, length2)
  let i = 0
  for (i; i < minlength; i++) {
    let a = parseInt(arr1[i]) || 0
    let b = parseInt(arr2[i]) || 0
    let diff = a - b
    if (diff !== 0) {
      return diff > 0 ? 1 : -1
    }
  }
  if (length1 === length2) {
    return 0
  } else if (length1 > length2) {
    for (let j = i; j < length1; j++) {
      if (parseInt(arr1[j]) !== 0) {
        return 1
      }
    }
    return 0
  } else {
    for (let j = i; j < length2; j++) {
      if (parseInt(arr2[j]) !== 0) {
        return -1
      }
    }
    return 0
  }
}

export default {
	msg,
	phoneVerify,
	idcardVerify, // 身份证校验
	imgurl,
	upload,
	hasEmptyValue,
	transitionLocation,
	baseheader: "https://qiniu-cdn.maeiyun.com/avatar.png",
	newDayDate,
	makeCall,
	chooseImage, // 选择图片
	chooseVideo,
	toUrl, // 跳转
	getLocation, // 定位
	getDate, //获取今天明天日期
	bigNumber,
	scanCode,
	modal,
	authorize,
	phoneType,
	luhnCheck,
	compareVersion
}